package tgc.rj.zz.controller;

import java.util.HashMap;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import tgc.rj.zz.custom.DatagridFormUtils;
import tgc.rj.zz.custom.LogUtils;
import tgc.rj.zz.entity.Bj;
import tgc.rj.zz.entity.Student;
import tgc.rj.zz.entity.SysRole;
import tgc.rj.zz.entity.SysUser;
import tgc.rj.zz.entity.Teacher;
import tgc.rj.zz.repository.RoleRepository;
import tgc.rj.zz.security.UserUtils;
import tgc.rj.zz.service.BjService;
import tgc.rj.zz.service.StudentService;
import tgc.rj.zz.service.SysUserService;
import tgc.rj.zz.service.TeacherService;

@Controller
@RequestMapping("/user")
public class UserController {
	@Autowired
	private SysUserService sysUserDAO;
	@Autowired
	private StudentService stuDAO;
	@Autowired
	private BjService bjDAO;
	@Autowired
	private RoleRepository roleDAO;
	@Autowired
	private TeacherService teacherDAO;
	@Autowired
	private UserUtils userUtils;
	@Autowired
	private LogUtils logUtils;
	/*
	 * 学生管理页面
	 */
	@RequestMapping("/stuAll")
	public String stuAll(ModelMap map) {
		List<Bj> bjs = bjDAO.findAll();
		map.put("bjs", bjs);
		return "user/stuAll";
	}
	
	/*
	 * 学生所有
	 * 因为前台传过来的数据是json数据，
	 * 所以在后台需要用工具类接收，返回前台
	 */
	@RequestMapping("/listStudent")
	@ResponseBody
	public Object listStudent(DatagridFormUtils custom) {
		Pageable pageable = custom.buildPageable();
		Page<Student> page = null;
		if(custom.getId()==null) {
			page = stuDAO.findAll(pageable);
		}else {
			page = stuDAO.findAll(custom.studentBuildSpes(), pageable);
		}
		HashMap<String, Object> result = DatagridFormUtils.getPageResult(page);
		return result ;
		 
	}
	/*
	 * 保存学生
	 * 新增和修改
	 */
	@RequestMapping("/studentSave")
	@ResponseBody
	public String studentSave(Integer bj_id,Student model) {
		Bj byId = bjDAO.findById(bj_id);
		model.setBj(byId);
		SysRole role = roleDAO.findById(2).get();
		BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
		model.setPassword(encoder.encode("111"));
		model.getRoles().add(role);
		model.setIdentity(1);
		stuDAO.save(model);
		SysUser user = userUtils.getUser();
		logUtils.log(user.getUsername(),user.getName(),"编辑学生");
		return "保存学生成功！";
	}

	/*
	 * 老师管理页面
	 */
	@RequestMapping("/teacherAll")
	public String teacherAll(ModelMap map) {
		return "user/teacherAll";
	}
	
	/*
	 * 老师所有
	 */
	@RequestMapping("/listTeacher")
	@ResponseBody
	public Object listTeacher(DatagridFormUtils custom) {
		Pageable pageable = custom.buildPageable();
		Page<Teacher> page = null;
		if(custom.getId()==null) {
			page = teacherDAO.findAll(pageable);
		}else {
				page = teacherDAO.findAll(custom.teacherBuildSpes(), pageable);
		}
		HashMap<String, Object> result = DatagridFormUtils.getPageResult(page);
		return result ;
		
	}
	
	/*
	 * 保存老师
	 * 新增和修改
	 */
	@RequestMapping("/teacherSave")
	@ResponseBody
	public String teacherSave(Teacher model) {
		SysRole role = roleDAO.findById(2).get();
		BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
		model.setPassword(encoder.encode("111"));
		model.getRoles().add(role);
		model.setIdentity(2);
		teacherDAO.save(model);
		SysUser user = userUtils.getUser();
		logUtils.log(user.getUsername(),user.getName(),"编辑老师");
		return "保存老师成功！";
	}

	/*
	 * 删除操作，读者公用
	 * 可批量删除
	 */
	@RequestMapping("/delete")
	@ResponseBody
	public void deleteStudent(String ids) {
		String[] split = ids.split(",");
		for(int i=0;i<split.length;i++) {
			sysUserDAO.deleteById(Integer.parseInt(split[i]));
		}
		SysUser user = userUtils.getUser();
		logUtils.log(user.getUsername(),user.getName(),"删除用户");
		
	}
	/*
	 * 重置密码，读者公用
	 * 默认密码111
	 */
	@RequestMapping("/reset")
	@ResponseBody
	public Object reset(Integer id) {
		SysUser sysUser = sysUserDAO.findById(id);
		BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
		sysUser.setPassword(encoder.encode("111"));
		sysUserDAO.save(sysUser);
		SysUser user = userUtils.getUser();
		logUtils.log(user.getUsername(),user.getName(),"重置密码");
		return "重置成功！默认密码111";
	}
	/*
	 * 用户个人信息
	 */
	@RequestMapping("/personal")
	public String personal(ModelMap map) {
		SysUser user= userUtils.getUser();
		Integer id = user.getId();
		if(user.getIdentity()==1) {
			Student stuid = stuDAO.findById(id);
			map.put("username", stuid.getUsername());
			map.put("name", stuid.getName());
			map.put("sex", stuid.getSex());
			map.put("age", stuid.getAge());
			map.put("phone", stuid.getPhone());
		}else {
			Teacher teacherid = teacherDAO.findById(id);
			map.put("username", teacherid.getUsername());
			map.put("name", teacherid.getName());
			map.put("sex", teacherid.getSex());
			map.put("age", teacherid.getAge());
			map.put("phone", teacherid.getPhone());
		}
		return "user/personal";
	}
	
	/*
	 * 判断用户名是否存在
	 */
	@RequestMapping("/only")
	@ResponseBody
	public Object only(String username) {
		SysUser sys = sysUserDAO.findByUsername(username);
		if(sys==null) {
			return "";
		}else {
			return "此账号已注册";
		}
	}
	/*
	 * 读者注册（老师和学生）
	 */
	
	@RequestMapping("/register")
	@ResponseBody
	public String register(Teacher teamodel,Integer bj_id,Student stumodel) {
		if(bj_id == null) {
			BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
			teamodel.setPassword(encoder.encode("111"));
			teamodel.setIdentity(2);
			SysRole role = roleDAO.findById(2).get();
			teamodel.getRoles().add(role);
			teacherDAO.save(teamodel);
		}else {
			Bj bjid = bjDAO.findById(bj_id);
			stumodel.setBj(bjid);
			BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
			stumodel.setPassword(encoder.encode("111"));
			stumodel.setIdentity(1);
			SysRole role = roleDAO.findById(2).get();
			stumodel.getRoles().add(role);
			stuDAO.save(stumodel);
		}
		return "👌已成功注册";
	}
	
}

